package threaduse;

/**
 * 模拟线程死锁
 */
public class DeadLock {
    public static void main(String[] args) {
        DeadLockDemo deadLock1 = new DeadLockDemo(true);
        DeadLockDemo deadLock2 = new DeadLockDemo(false);

        deadLock1.start();
        deadLock2.start();

        deadLock1.interrupt();
    }
}

class DeadLockDemo extends Thread {
    static Object lock1 = new Object(); // 保证多线程，共享一个对象，这里使用 static
    static Object lock2 = new Object();
    boolean flag;

    public DeadLockDemo(boolean flag) {
        this.flag = flag;
    }

    /*
        分析业务逻辑：
            1. 当 new DeadLockDemo(true); deadLock1 拿到了 lock1 锁
            2. 当 new DeadLockDemo(false); deadLock2 拿到了 lock2 锁
            3. 两个线程如果想向下走就要获取对方手里的 锁资源 但现在很明显 都获取不到 除非一方先释放锁
     */
    public void run() {
        if (flag){
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() + "进入1");
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + "进入2");
                }
            }
        }else {
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "进入3");
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "进入4");
                }
            }
        }
    }
}
